<template>
  <view class="page-container">
    <wd-popup v-model="props.showEditTouristAddress" :modal="false" custom-style="border-radius:12rpx;" position="bottom" @enter="initEvent">
      <view class="popup-container pd20">
        <view class="header-container flex items-center justify-between">
          <wd-icon name="arrow-left" size="22px" @click="handleGoBack(false)"></wd-icon>
          <view class="title">编辑收货地址</view>
          <text class="save-btn" @click="handleSaveTouristAddress">保存</text>
        </view>
        <view class="info-container">
          <wd-input
              type="text"
              label="姓名"
              v-model="touristAddress.name"
              placeholder=" "
              label-width="30px"
              custom-class="custom-input-container-class"
          />

          <wd-input
              type="number"
              label="联系方式"
              v-model="touristAddress.tel"
              placeholder=" "
              label-width="56px"
              custom-class="custom-input-container-class"
          />
          <wd-input
              type="text"
              label="所在地区"
              v-model="touristAddress.area"
              placeholder=" "
              label-width="56px"
              :disabled="true"
              custom-class="custom-input-container-class"
              custom-input-class="custom-input-content-container-class"
              @click="openAreaPicker"
          >
            <template #suffix>
              <wd-icon name="arrow-right" size="22px"></wd-icon>
            </template>
          </wd-input>
          <wd-input
              type="text"
              label="详细地区与门牌号"
              v-model="touristAddress.address"
              placeholder=" "
              label-width="112px"
              custom-class="custom-input-container-class"
          />
        </view>
        <view
            class="set-default-address-container"
            @click="touristAddress.isDefault = !touristAddress.isDefault"
        >
          <radio
              :value="1"
              :checked="touristAddress.isDefault"
              color="#1b9c61"
              style="transform: scale(0.7)"
          />
          <text>设为默认地址</text>
        </view>
      </view>
    </wd-popup>
    <wd-popup v-model="showPopupArea" custom-style="border-radius:12rpx;" position="bottom">
      <wd-picker-view :columns="columns" v-model="value" :column-change="onChangeDistrict"  @change="changeArea"/>
      <view class="pd20 flex justify-between">
        <wd-button type="info" custom-class="custom-btn-class" @click="cancelSetArea">取消</wd-button>
        <wd-button type="success" custom-class="custom-btn-class" @click="confirmSetArea">确定</wd-button>
      </view>
      <view style="height:30px"></view>
    </wd-popup>
  </view>
</template>

<script setup>
import {addTouristAddress, editorTouristAddress} from "@/api/specialty";

  defineOptions({
    options: {
      styleIsolation: 'shared'
    }
  })
  import {ref} from "vue";

  const props = defineProps({
    showEditTouristAddress: {
      type: Boolean,
      default: false
    },
    editorTouristAddObj: {
      type: Object,
      default: {}
    }
  });
  const emits = defineEmits(["closeEditTouristAddress"]);

  watch((props.editorTouristAddObj),(value) => {
    console.log(value,'watch -- editor tourist add obj');
    if(value.id) {
      let {address, city, district, id, isDefault, name, province, tel} = value;
      touristAddress.value = {
        id,
        name,
        tel,
        area: province + city + district,
        province,
        city,
        district,
        address,
        isDefault
      };
      provinceCityDistrictArr.value = [province, city, district];
    }
  },{deep:true});

  const touristAddress = ref({
    id: "",
    name: "",
    tel: "",
    area: "",
    province: "",
    city: "",
    district: "",
    address: "",
    isDefault: 0
  });
  const provinceList = ref([]);
  const columns = ref([]);
  const showPopupArea =ref(false);
  const value = ref(['110000', '110100', '110101']);
  const provinceCityDistrictArr = ref(["北京市","市辖区","东城区"]);



  const onChangeDistrict = (pickerView, value, columnIndex, resolve) => {
    const item = value[columnIndex]
    if (columnIndex === 0) {
      pickerView.setColumnData(1, provinceList.value[item.value])
      pickerView.setColumnData(2, provinceList.value[provinceList.value[item.value][0].value])
    } else if (columnIndex === 1) {
      pickerView.setColumnData(2, provinceList.value[item.value])
    }
    resolve()
  };
  const cancelSetArea = () => {
    showPopupArea.value = false;
  };
  const confirmSetArea = () => {
    touristAddress.value.area = provinceCityDistrictArr.value.join("");
    touristAddress.value.province = provinceCityDistrictArr.value[0];
    touristAddress.value.city = provinceCityDistrictArr.value[1];
    touristAddress.value.district = provinceCityDistrictArr.value[2];
    showPopupArea.value = false;
  };
  const changeArea = (event) => {
    console.log(event,'event');
    console.log(event.picker.getLabels(),'event');
    provinceCityDistrictArr.value = event.picker.getLabels();
  };
  const displayFormat = (items) => {
    return items
        .map((item) => {
          return item.label
        })
        .join('-')
  }
  const handleSaveTouristAddress = async () => {
    const { name, tel, area, address, isDefault, id } = touristAddress.value;
    const validations = [
      [name, "请完善收货人姓名"],
      [tel, "请完善收货人联系方式"],
      [area, "请选择收货人所在区域"],
      [address, "请完善收货人详细地址与门牌号"]
    ];

    const tipContent = validations.find(([field]) => !field)?.[1];

    if (tipContent) {
      uni.showToast({
        icon: "none",
        title: tipContent
      });
      return;
    }
    // 新增
    if(!touristAddress.value.id) {
      await addTouristAddress({
        name,
        tel,
        province: provinceCityDistrictArr.value[0],
        city: provinceCityDistrictArr.value[1],
        district: provinceCityDistrictArr.value[2],
        address,
        isDefault: isDefault ? 1 : 0
      }).then(res => {
        handleGoBack(false);
      });
    }
    // 修改
    else {
      await editorTouristAddress({
        id,
        name,
        tel,
        province: provinceCityDistrictArr.value[0],
        city: provinceCityDistrictArr.value[1],
        district: provinceCityDistrictArr.value[2],
        address,
        isDefault: isDefault ? 1 : 0
      }).then(res => {
        handleGoBack(true);
      });
    }
  };
  const handleGoBack = (isUpdateTouristAddList) => {
    for (let valueKey in touristAddress.value) {
      if(valueKey === "isDefault") {
        touristAddress.value[valueKey] = 0;
      }else {
        touristAddress.value[valueKey] = "";
      }
    }
    emits("closeEditTouristAddress",{isUpdateTouristAddList});
  };
  const openAreaPicker = () => {
    showPopupArea.value = true;
  };
  const queryProvinceList = () => {
    uni.request({
      url: "https://api.jowong.com/static/js/province.js",
      success:(res) => {
        let {data} = res;
        provinceList.value = data;

        const district = { '0': [] };

        data.forEach(p => {
          const provinceItem = { label: p.name, value: p.code };
          district['0'].push(provinceItem);
          district[p.code] = [];

          if(p.city && p.city.length > 0) {
            p.city.forEach(c => {
              const cityItem = { label: c.name, value: c.code };
              district[p.code].push(cityItem);
              district[c.code] = [];

              if (c.area && Array.isArray(c.area)) {
                c.area.forEach(a => {
                  district[c.code].push({ label: a.name, value: a.code });
                });
              }
            });
          }
        });
        provinceList.value = district;
        columns.value = [district[0], district[district[0][0].value], district[district[district[0][0].value][0].value]]
      }
    })
  };
  
  const initEvent = () => {
	  queryProvinceList();
  };
  </script>

<style lang="scss" scoped>
.page-container {
  .popup-container {
    height: 60vh;
    background: linear-gradient(180deg, rgba(204,234,214,1) 0%, rgba(226,243,231,.5) 10%, rgba(255,255,255,1) 100%);
    .header-container {
      padding-bottom: 26rpx;
      margin-bottom: 20rpx;
      border-bottom: 1rpx solid #C0C2B3;
      .title {
        font-size: 29rpx;
        font-weight: bold;
      }
      .save-btn {
        padding: 10rpx 31rpx;
        font-size: 22rpx;
        border-radius: 7rpx;
        border: 1rpx solid #508963;
      }
    }
    .set-default-address-container {
      text-align: end;
      margin-top: 50rpx;
      text {
        font-size: 25rpx;
      }
    }
  }
  :deep(.custom-input-container-class) {
    background-color: transparent;
    padding: 27.5rpx 0;
    border-bottom: 1rpx solid #C0C2B3;
  }
  :deep(.custom-input-content-container-class) {
    color: black !important;
  }
  :deep(.custom-btn-class) {
    width: 48%;
    border-radius: 10rpx;
  }
}
</style>
